package com.example.deepai.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import jakarta.annotation.PostConstruct;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.time.Instant;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class ScreenCaptureService {

    @Value("${adb.path:adb}")
    private String adbPath;

    @Value("${hdc.path:hdc}")
    private String hdcPath;

    @Value("${screenshots.directory}")
    private String screenshotsDirectory;
    
    private Path screenshotsFolder;
    
    @PostConstruct
    public void init() {
        screenshotsFolder = Paths.get(screenshotsDirectory);
        try {
            if (!Files.exists(screenshotsFolder)) {
                Files.createDirectories(screenshotsFolder);
            }
            log.info("截图保存目录: {}", screenshotsFolder.toAbsolutePath());
        } catch (IOException e) {
            log.error("创建截图文件夹失败", e);
        }
    }

    public String captureScreen() throws IOException, InterruptedException {
        if (isHarmonyOSDevice()) {
            return captureHarmonyScreen();
        } else {
            return captureAndroidScreen();
        }
    }

    private String captureAndroidScreen() throws IOException, InterruptedException {
        String fileName = "screen_" + Instant.now().getEpochSecond() + ".png";
        Path filePath = screenshotsFolder.resolve(fileName);
        
        log.info("Android截图文件路径: {}", filePath.toAbsolutePath());
        
        ProcessBuilder processBuilder = new ProcessBuilder();
        
        if (System.getProperty("os.name").toLowerCase().contains("windows")) {
            log.debug("ADB路径: {}", adbPath);
            processBuilder.command(adbPath, "exec-out", "screencap", "-p");
        } else {
            processBuilder.command("sh", "-c", adbPath + " exec-out screencap -p");
        }

        processBuilder.redirectOutput(filePath.toFile());
        
        return executeAndVerify(processBuilder, filePath);
    }

    private String captureHarmonyScreen() throws IOException, InterruptedException {
        // 1. 执行截图命令并等待文件生成
        executeCommand(hdcPath, "shell", "snapshot_display");
        Thread.sleep(1000); // 等待截图文件生成
        
        // 2. 列出远程文件确认是否生成
        ProcessBuilder listBuilder = new ProcessBuilder(hdcPath, "shell", "ls", "-l", "/data/local/tmp/");
        Process listProcess = listBuilder.start();
        String listOutput = new String(listProcess.getInputStream().readAllBytes());
        log.info("远程文件列表: {}", listOutput);
        
        // 3. 获取最新的截图文件（根据文件名中的时间戳）
        String latestSnapshot = listOutput.lines()
            .filter(line -> line.contains("snapshot_") && line.contains(".jpeg"))
            .map(line -> {
                String[] parts = line.split("\\s+");
                return parts[parts.length - 1];
            })
            .max((a, b) -> {
                // 从文件名中提取时间戳部分进行比较
                String timeA = a.substring(a.indexOf("_") + 1, a.lastIndexOf("."));
                String timeB = b.substring(b.indexOf("_") + 1, b.lastIndexOf("."));
                return timeA.compareTo(timeB);
            })
            .orElseThrow(() -> new IOException("未找到截图文件"));
            
        String latestRemotePath = "/data/local/tmp/" + latestSnapshot;
        log.info("找到最新截图: {}", latestRemotePath);
        
        // 4. 接收文件
        executeCommand(hdcPath, "file", "recv", latestRemotePath);
        
        // 5. 移动文件到目标目录
        String fileName = "screen_" + Instant.now().getEpochSecond() + ".jpeg";
        Path filePath = screenshotsFolder.resolve(fileName);
        Path downloadedFile = Paths.get(latestSnapshot);
        
        if (Files.exists(downloadedFile)) {
            Files.move(downloadedFile, filePath, StandardCopyOption.REPLACE_EXISTING);
            log.info("鸿蒙截图已保存: {}", filePath.toAbsolutePath());
            return filePath.toAbsolutePath().toString();
        }
        
        throw new IOException("鸿蒙截图失败：文件未生成");
    }

    private boolean isHarmonyOSDevice() throws IOException, InterruptedException {
        try {
            ProcessBuilder processBuilder = new ProcessBuilder(hdcPath, "shell", "uname", "-a");
            Process process = processBuilder.start();
            String output = new String(process.getInputStream().readAllBytes());
            process.waitFor(5, TimeUnit.SECONDS);
            
            // 检查输出是否包含 HarmonyOS 或 HongMeng 关键字
            String osInfo = output.trim().toLowerCase();
            return osInfo.contains("harmonyos") || osInfo.contains("hongmeng");
            
        } catch (Exception e) {
            log.debug("未检测到鸿蒙设备: {}", e.getMessage());
            return false;
        }
    }

    private String executeAndVerify(ProcessBuilder processBuilder, Path filePath) throws IOException, InterruptedException {
        log.info("执行命令: {}", String.join(" ", processBuilder.command()));
        Process process = processBuilder.start();
        
        boolean completed = process.waitFor(30, TimeUnit.SECONDS);
        if (!completed) {
            process.destroyForcibly();
            throw new IOException("截图超时");
        }

        int exitCode = process.exitValue();
        if (exitCode != 0) {
            String errorOutput = new String(process.getErrorStream().readAllBytes());
            log.error("截图失败，退出码: {}，错误信息: {}", exitCode, errorOutput);
            throw new IOException("截图失败，退出码: " + exitCode + "，错误信息: " + errorOutput);
        }

        if (Files.exists(filePath) && Files.size(filePath) > 0) {
            String absolutePath = filePath.toAbsolutePath().toString();
            log.info("截图成功，绝对路径: {}", absolutePath);
            return absolutePath;
        }

        throw new IOException("截图失败，文件未生成");
    }

    private void executeCommand(String... command) throws IOException, InterruptedException {
        ProcessBuilder processBuilder = new ProcessBuilder(command);
        log.info("执行命令: {}", String.join(" ", command));
        
        Process process = processBuilder.start();
        boolean completed = process.waitFor(30, TimeUnit.SECONDS);
        
        if (!completed) {
            process.destroyForcibly();
            throw new IOException("命令执行超时: " + String.join(" ", command));
        }
        
        int exitCode = process.exitValue();
        if (exitCode != 0) {
            String errorOutput = new String(process.getErrorStream().readAllBytes());
            throw new IOException("命令执行失败: " + String.join(" ", command) + 
                                ", 退出码: " + exitCode + ", 错误信息: " + errorOutput);
        }
    }
}